package Maximum;


import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;

import java.util.Date;



import jess.Fact;
import jess.JessException;
import jess.RU;
import jess.Userfunction;
import jess.Value;
import jess.ValueVector;
import jess.Context;



public class Maximum implements Userfunction {
	
	public String getName(){
		return "Maximum";
	}
	public Value call(ValueVector vv, Context context) {				
		try{
			if (vv.size() != 4)
				throw new JessException("Average",
				"Wrong number of arguments", vv.size()-1);
			else
			{
				int dataId=vv.get(1).intValue((jess.Context) context);
				String initialTime=vv.get(1).stringValue((jess.Context) context);
				String finalTime=vv.get(2).stringValue((jess.Context) context);
				
				Object[] arguments = new Object[3];
				  arguments[0] = dataId;
				  arguments[1]= initialTime;
				  arguments[2]= finalTime;
				
				System.out.println("Max agent has id"+dataId+"and wants data for initial time" +initialTime+" and final time" +finalTime);
			
				 // Get a hold on JADE runtime
				 jade.core.Runtime rt = jade.core.Runtime.instance();

			      // Exit the JVM when there are no more containers around
			      rt.setCloseVM(true);

				  // Create a default profile
				  Profile p = new ProfileImpl(false);
				  //p.setParameter(Profile.MAIN, "false");

				  // Create a new non-main container, connecting to the default
				  // main container (i.e. on this host, port 1099)
			      System.out.println("Launching the agent container ..."+p);
				  AgentContainer ac = rt.createAgentContainer(p);

				  // Create a new agent, a DummyAgent
				  CondVar startUpLatch = new CondVar();
				  Object o[]=new Object[2];
				  o[0]=startUpLatch;
				  o[1]=arguments;
				  AgentController agent = ac.createNewAgent("MaxAgent", "Maximum.MaxAgent", o);

				  // Fire up the agent
				  System.out.println("Server agent it's being started");
				  agent.start();			
				  float[] data=null;
				  
				  try {
						data=startUpLatch.waitOn();
					      }
					      catch(InterruptedException ie) {
						ie.printStackTrace();
					      }
			
			for(int i=0;i<data.length;i++)
			{
			Fact f=new Fact("data",((jess.Context) context).getEngine());
			f.setSlotValue("value",new Value(data[i],RU.INTEGER));
			f.setSlotValue("time", new Value((new Date()).toString(),RU.STRING));
			System.out.println(data[i]);
			((jess.Context) context).getEngine().assertFact(f);
			}
				
			}
			
		}catch(Exception e)
		{
			e.printStackTrace();
		}	
		return null;
		}
	
}
